﻿using RestSharp;
using System;
using System.Configuration;
using System.Linq;
using System.Timers;
using Topshelf;

namespace Newbe.TestDirector.Notification.KeepAlive
{
    class Program
    {
        public static void Main()
        {
            HostFactory.Run(x =>
            {
                x.Service<TownCrier>(s =>
                {
                    s.ConstructUsing(name => new TownCrier());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();
                x.SetDescription("该服务用于确保td邮件提醒站点的程序池始终处于激活状态。");
                x.SetDisplayName("td邮件提醒应用程序池激活服务");
                x.SetServiceName("Newbe.TestDirector.Notification.KeepAlive");
            });
        }
    }

    public class TownCrier
    {
        readonly Timer _timer;

        public TownCrier()
        {
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += _timer_Elapsed;
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var settings = ConfigurationManager.AppSettings;
            foreach (var url in settings.AllKeys.Where(x => x.StartsWith("url")).Select(x => settings[x]))
            {
                var restClient = new RestClient
                {
                    BaseUrl = new Uri(url)
                };
                var req = new RestRequest(Method.GET);
                restClient.Get(req);
            }
            Console.WriteLine("ok");
        }

        public void Start()
        {
            _timer.Start();
        }

        public void Stop()
        {
            _timer.Stop();
        }
    }
}
